package demo00.excise;

import java.util.Random;
import java.util.Scanner;

public class Demo01 {

    public static void main(String[] args) {
        T1 t1 = new T1();
        T2 t2 = new T2(t1);

        new Thread(() -> { t1.hello(); }).start();
        new Thread(() -> { t2.listen(); }).start();
    }
}

class T1 {
    private boolean loop = true;
    private Random random = new Random();

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    public void hello() {
        while (loop) {
            // random.nextInt(100);
            System.out.println(Thread.currentThread().getName() + random.nextInt(100));

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("A 线程退出");
    }
}

class T2 {
    private T1 t1;
    private Scanner scanner = new Scanner(System.in);

    public T2(T1 t) {
        this.t1 = t;
    }

    public void listen() {
        System.out.println("Please enter(Q) to stop thread t1...");
        while (scanner.hasNext()) {
            char key = scanner.next().toUpperCase().charAt(0);
            System.out.println(key);
            if ('Q' == key) {
                t1.setLoop(false);
                break;
            }
        }

        System.out.println("B 线程退出");
    }
}
